package com.sijia.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sijia.reggie.comment.CustomerException;
import com.sijia.reggie.comment.R;
import com.sijia.reggie.dto.SetmealDto;
import com.sijia.reggie.entity.Setmeal;
import com.sijia.reggie.entity.SetmealDish;
import com.sijia.reggie.mapper.SetmealMapper;
import com.sijia.reggie.service.SetmealDishService;
import com.sijia.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.stream.Collectors;

/**
 * @author 杨思佳
 * @version 1.0
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService sds;



    @Override
    public R<String> addSetmeal(SetmealDto setmealDto) {
        this.save(setmealDto);
        Long id = setmealDto.getId();
        for (SetmealDish sd : setmealDto.getSetmealDishes()){
            sd.setSetmealId(id);
        }
        sds.saveBatch(setmealDto.getSetmealDishes());
        return R.success("保存成功");
    }


    /**
     *
     * 删除套餐以及相关表
     * @param ids
     * @return
     */
    @Override
    public R<String> deleteSetmeal(Long[] ids) {
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId, ids);
        queryWrapper.eq(Setmeal::getStatus, 1);
        int count = this.count(queryWrapper);
        if (count > 0){
            throw new CustomerException("套餐正在售卖中，请停售后操作");
        }
        this.removeByIds(Arrays.stream(ids).collect(Collectors.toList()));

        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(SetmealDish::getSetmealId, ids);
        sds.remove(wrapper);
        return R.success("删除成功");
    }

    @Override
    public R<String> updateSetmeal(SetmealDto setmealDto) {
        this.updateById(setmealDto);
        Long setmealId = setmealDto.getId();
        for (SetmealDish sd : setmealDto.getSetmealDishes()){
            sd.setSetmealId(setmealId);
        }
        //由于套餐的菜品更新涉及到删除，更新，增加的多个sql操作，这里直接将当前套餐下的菜品全部删除再保存
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, setmealId);
        sds.remove(queryWrapper);
        sds.saveBatch(setmealDto.getSetmealDishes());
        return R.success("套餐信息更新成功");
    }
}
